import {ToastAndroid} from 'react-native';

export const request = (url, config) => {
  return fetch(url, config)
    .then(res => {
      if (res.ok) {
        return res.json();
      } else {
        throw Error('fetch 封装处报错...');
      }
    })
    .then(resJson => {
      console.log(resJson);
      if (resJson.code === 100) {
        ToastAndroid.showWithGravity(resJson.msg, ToastAndroid.SHORT, ToastAndroid.TOP);
        return resJson;
      } else {
        ToastAndroid.showWithGravity(resJson.msg, ToastAndroid.SHORT, ToastAndroid.TOP);
      }
    })
    .catch(error => {
      console.log(url + '接口出错...', error);
    });
};

// get调用方法：
// get('https://xxx/xxx/xxx')
export const get = (url, params) => {
  console.log('params:', params);
  if (params) {
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach(key => {
      paramsArray.push(key + '=' + params[key]);
    });
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&');
    } else {
      url += '&' + paramsArray.join('&');
    }
  }
  return request(url, {method: 'GET'});
};

// post调用方法：
// post('https://xxx/xxx/xxx',{name:'',age:''})
export const post = (url, params) => {
  return request(url, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify(params),
  });
};
